//
//  BaseToastView.m
//  OoowinQuick
//
//  Created by ooowin-ios on 16/4/28.
//  Copyright © 2016年 XQ. All rights reserved.
//

#import "BaseToastView.h"

@implementation BaseToastView

#define TOAST_LONG  2000
#define TOAST_SHORT 1000

#define kCBToastPadding         20
#define kCBToastMaxWidth        220
#define kCBToastCornerRadius    5.0
#define kCBToastFadeDuration    0.5
#define kCBToastTextColor       [UIColor whiteColor]
#define kCBToastBottomPadding   30
#define TOAST_DURATION          3

+ (void)showToast:(NSString *)message withDuration:(NSUInteger)duration {
    dispatch_async(dispatch_get_main_queue(), ^{
        // build the toast label
        UILabel *toast = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
        toast.text = message;
        toast.backgroundColor = [UIColor colorWithWhite:0.0f alpha:0.6f];
        toast.textColor = kCBToastTextColor;
        toast.numberOfLines = 1000;
        toast.tag = 1024;
        toast.textAlignment = NSTextAlignmentCenter;
        toast.lineBreakMode = NSLineBreakByWordWrapping;
        toast.font = [UIFont systemFontOfSize:14.0f];
        toast.layer.cornerRadius = kCBToastCornerRadius;
        toast.layer.masksToBounds = YES;
        
        // resize based on message
        CGSize maximumLabelSize = CGSizeMake(kCBToastMaxWidth, 9999);
        CGSize expectedLabelSize = [toast.text boundingRectWithSize:maximumLabelSize
                                                            options:NSStringDrawingUsesLineFragmentOrigin
                                                         attributes:@{NSFontAttributeName:toast.font}
                                                            context:nil].size;
        //adjust the label to the new height
        CGRect newFrame = toast.frame;
        newFrame.size = CGSizeMake(expectedLabelSize.width + kCBToastPadding,
                                   expectedLabelSize.height + kCBToastPadding);
        toast.frame = newFrame;
        
        // add the toast to the root window (so it overlays everything)
        if ([toast.text length] > 0) {
            [KEY_WINDOW addSubview:toast];
            
            // get the window frame to determine placement
            CGRect windowFrame = KEY_WINDOW.frame;
            
            // align the toast properly
            toast.center = CGPointMake(windowFrame.size.width / 2, windowFrame.size.height / 2);
            
            // round the x/y coords so they aren't 'split' between values (would appear blurry)
            toast.frame = CGRectMake(round(toast.frame.origin.x),
                                     round(toast.frame.origin.y),
                                     toast.frame.size.width,
                                     toast.frame.size.height);
            
            // set up the fade-in
            [UIView beginAnimations:nil context:nil];
            [UIView setAnimationDuration:kCBToastFadeDuration];
            
            // values being aninmated
            toast.alpha = 1.0f;
            
            // perform the animation
            [UIView commitAnimations];
            
            // calculate the delay based on fade-in time + display duration
            NSTimeInterval delay = duration;
            
            // set up the fade out (to be performed at a later time)
            [UIView beginAnimations:nil context:nil];
            [UIView setAnimationDelay:delay];
            [UIView setAnimationDuration:kCBToastFadeDuration];
            [UIView setAnimationDelegate:toast];
            [UIView setAnimationDidStopSelector:@selector(removeFromSuperview)];
            
            // values being animated
            toast.alpha = 0.0f;
            
            // commit the animation for being performed when the timer fires
            [UIView commitAnimations];
        }
    });
}

+ (void)showToast:(NSString *)message imgType:(NSInteger)type withDuration:(NSUInteger)duration {
    dispatch_async(dispatch_get_main_queue(), ^{
        // build the toast label
        UIView *toastView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 40,40)];
        toastView.backgroundColor = [UIColor colorWithWhite:0.0f alpha:0.6f];;
        toastView.layer.cornerRadius = kCBToastCornerRadius;
        toastView.layer.masksToBounds = YES;
        toastView.tag = 1024;
        
        // 图片添加
        UIImageView *imageview = [[UIImageView alloc] initWithFrame:CGRectMake(kCBToastPadding/2, kCBToastPadding/2, 15, 15)];
        if (type == 0) {
            imageview.image = [UIImage imageNamed:@"alert_warn"];
        } else {
            imageview.image = [UIImage imageNamed:@"alert_ok"];
        }
        [toastView addSubview:imageview];
        
        // label添加
        UILabel *toast = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
        toast.backgroundColor = [UIColor clearColor];
        toast.text = message;
        toast.textColor = kCBToastTextColor;
        toast.numberOfLines = 1000;
        toast.textAlignment = NSTextAlignmentCenter;
        toast.lineBreakMode = NSLineBreakByWordWrapping;
        toast.font = [UIFont systemFontOfSize:14.0f];
        
        // resize based on message
        CGSize maximumLabelSize = CGSizeMake(kCBToastMaxWidth, 9999);
        CGSize expectedLabelSize = [toast.text boundingRectWithSize:maximumLabelSize
                                                            options:NSStringDrawingUsesLineFragmentOrigin
                                                         attributes:@{NSFontAttributeName:toast.font}
                                                            context:nil].size;
        //        //adjust the label to the new height
        toast.frame = CGRectMake(kCBToastPadding+15, kCBToastPadding/2 - 1.5, expectedLabelSize.width, expectedLabelSize.height);
        toastView.frame = CGRectMake(0, 0, expectedLabelSize.width+kCBToastPadding*1.5+15, expectedLabelSize.height+kCBToastPadding);
        
        [toastView addSubview:toast];
        
        // add the toast to the root window (so it overlays everything)
        if ([message length] > 0) {
            [KEY_WINDOW addSubview:toastView];
            
            // get the window frame to determine placement
            CGRect windowFrame = KEY_WINDOW.frame;
            
            // align the toast properly
            toastView.center = CGPointMake(windowFrame.size.width / 2, windowFrame.size.height / 2);
            
            // round the x/y coords so they aren't 'split' between values (would appear blurry)
            toastView.frame = CGRectMake(round(toastView.frame.origin.x),
                                         round(toastView.frame.origin.y),
                                         toastView.frame.size.width,
                                         toastView.frame.size.height);
            
            // set up the fade-in
            [UIView beginAnimations:nil context:nil];
            [UIView setAnimationDuration:kCBToastFadeDuration];
            
            // values being aninmated
            toastView.alpha = 1.0f;
            
            // perform the animation
            [UIView commitAnimations];
            
            // calculate the delay based on fade-in time + display duration
            NSTimeInterval delay = duration;
            
            // set up the fade out (to be performed at a later time)
            [UIView beginAnimations:nil context:nil];
            [UIView setAnimationDelay:delay];
            [UIView setAnimationDuration:kCBToastFadeDuration];
            [UIView setAnimationDelegate:toastView];
            [UIView setAnimationDidStopSelector:@selector(removeFromSuperview)];
            
            // values being animated
            toastView.alpha = 0.0f;
            
            // commit the animation for being performed when the timer fires
            [UIView commitAnimations];
        }
    });
}

+ (void)showToast:(NSString *)message {
    dispatch_async(dispatch_get_main_queue(), ^{
        // build the toast label
        UILabel *toast = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
        toast.text = message;
        toast.backgroundColor = [UIColor colorWithWhite:0.0f alpha:0.6f];
        toast.textColor = kCBToastTextColor;
        toast.numberOfLines = 1000;
        toast.tag = 1024;
        toast.textAlignment = NSTextAlignmentCenter;
        toast.lineBreakMode = NSLineBreakByWordWrapping;
        toast.font = [UIFont systemFontOfSize:14.0f];
        toast.layer.cornerRadius = kCBToastCornerRadius;
        toast.layer.masksToBounds = YES;
        
        // resize based on message
        CGSize maximumLabelSize = CGSizeMake(kCBToastMaxWidth, 9999);
        CGSize expectedLabelSize = [toast.text boundingRectWithSize:maximumLabelSize
                                                            options:NSStringDrawingUsesLineFragmentOrigin
                                                         attributes:@{NSFontAttributeName:toast.font}
                                                            context:nil].size;
        //adjust the label to the new height
        CGRect newFrame = toast.frame;
        newFrame.size = CGSizeMake(expectedLabelSize.width + kCBToastPadding,
                                   expectedLabelSize.height + kCBToastPadding);
        toast.frame = newFrame;
        
        // add the toast to the root window (so it overlays everything)
        if ([toast.text length] > 0) {
            [KEY_WINDOW addSubview:toast];
            
            // get the window frame to determine placement
            CGRect windowFrame = KEY_WINDOW.frame;
            
            // align the toast properly
            toast.center = CGPointMake(windowFrame.size.width / 2, windowFrame.size.height / 2);
            
            // round the x/y coords so they aren't 'split' between values (would appear blurry)
            toast.frame = CGRectMake(round(toast.frame.origin.x),
                                     round(toast.frame.origin.y),
                                     toast.frame.size.width,
                                     toast.frame.size.height);
            
            // set up the fade-in
            [UIView beginAnimations:nil context:nil];
            [UIView setAnimationDuration:kCBToastFadeDuration];
            
            // values being aninmated
            toast.alpha = 1.0f;
            
            // perform the animation
            [UIView commitAnimations];
            
            // calculate the delay based on fade-in time + display duration
            NSTimeInterval delay = TOAST_DURATION;
            
            // set up the fade out (to be performed at a later time)
            [UIView beginAnimations:nil context:nil];
            [UIView setAnimationDelay:delay];
            [UIView setAnimationDuration:kCBToastFadeDuration];
            [UIView setAnimationDelegate:toast];
            [UIView setAnimationDidStopSelector:@selector(removeFromSuperview)];
            
            // values being animated
            toast.alpha = 0.0f;
            
            // commit the animation for being performed when the timer fires
            [UIView commitAnimations];
        }
    });
}

+ (void)dismissToast {
    UIView *toast = (UIView *)KEY_WINDOW.subviews.lastObject;
    
    if (toast.tag == 1024) {
        [toast removeFromSuperview];
    }
}
+ (void)hideLoadIng:(UIView *)superView {
    if (superView == nil) {
        superView = (UIView*)[UIApplication sharedApplication].keyWindow;
    }
    
    //隐藏之前的toast
    NSArray *hudArr = [MBProgressHUD allHUDsForView:superView];
    for (MBProgressHUD *oldHud in hudArr) {
        if (oldHud.tag == YLToastTag) {
            [oldHud hideAnimated:YES];
        }
    }
}


+ (void)showToastWithText:(NSString *)text Type:(YLToastType)type ToView:(UIView *)view {
    if (view) {
        [self showToastWithText:text Type:type ToView:view BottomMargin:0.5*view.bounds.size.height];
    }else{
        [self showToastWithText:text Type:type ToView:view BottomMargin:0.5*[UIScreen mainScreen].bounds.size.height];
    }
}

+ (void)showToastWithText:(NSString *)text Type:(YLToastType)type ToView:(UIView *)view BottomMargin:(CGFloat)margin {
    if (view == nil) {
        view = (UIView*)[UIApplication sharedApplication].keyWindow;
    }
    
    //隐藏之前的toast
    NSArray *hudArr = [MBProgressHUD allHUDsForView:view];
    for (MBProgressHUD *oldHud in hudArr) {
        if (oldHud.tag == YLToastTag) {
            [oldHud hideAnimated:YES];
        }
    }
    //显示新的toast
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
    
    //标记一下是toast类型hud
    hud.tag = YLToastTag;
    hud.backgroundColor = [UIColor clearColor];

    //设置toast属性
    hud.userInteractionEnabled = NO;
    hud.mode = MBProgressHUDModeText;
    hud.detailsLabel.text = text;
    hud.detailsLabel.font = [UIFont systemFontOfSize:14];
    hud.detailsLabel.textColor = [UIColor colorWithHexString:@"#FFFFFF"];
    hud.bezelView.backgroundColor = [UIColor colorWithHexString:@"#171A1D" withAlpha:0.9];
//    hud.layer.cornerRadius = kCBToastCornerRadius;
//    hud.layer.masksToBounds = YES;
    hud.cornerRadius = 8;
    hud.margin = 10;
    if (view) {
        hud.yOffset = 0.5*view.bounds.size.height -18 - margin;
    } else {
        hud.yOffset = 0.5*[UIScreen mainScreen].bounds.size.height -18 - margin;
    }
 
    hud.removeFromSuperViewOnHide = YES;
    
    // 隐藏toast
    if (type == YLToastTypeShort) {
//          [hud hide:YES afterDelay:2];
                [hud hideAnimated:YES afterDelay:2];
    }else if (type == YLToastTypeLong) {
//          [hud hide:YES afterDelay:3];
                [hud hideAnimated:YES afterDelay:3];
    }else if (type == YLToastTypePermanent) {
        [hud show:YES];
    }
}

@end


